//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
//THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 
//BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
//OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var addSearchFilterMenu = function (refineBy) {

    $(function () {
        // function to extract a query parameter from the URL
        // from http://stackoverflow.com/questions/523266/how-can-i-get-a-specific-parameter-from-location-search
        function getParameter(paramName) {
            var searchString = window.location.search.substring(1),
                i, val, params = searchString.split("&");

            for (i = 0; i < params.length; i++) {
                val = params[i].split("=");
                if (val[0] == paramName) {
                    return val[1];
                }
            }
            return null;
        }

        var q = getParameter('q');
        
        var rows = $("table.trim-list tr");
        refineBy = refineBy || [];

        if (rows.length > 1 && refineBy.length > 0) {

            var td = $('<td/>')
                .addClass('well')
                .attr('rowspan', Math.ceil(refineBy.length / 2))
                .appendTo(rows.eq(1));

            var heading = $('<h4>Refine by</h4>').appendTo(td);

            var list = $('<ul></ul>')
                .addClass('nav nav-list')
                .attr('style', 'width:120px;')
                .appendTo(td);

            var msg = $('<h5>checking filters...</h4>').appendTo(td);
            var count = 0;
            $.each(refineBy, function (i) {
                var li = $('<li/>')
                    .hide()
                    .appendTo(list);

                if (q) {
                    newUrl = window.location.href.replace('q=' + q, 'q=' + q + ' AND ' + refineBy[i].Clause + ":" + refineBy[i].Query);
                } else {
                    newUrl = (window.location.href + '&' + refineBy[i].Clause + "=" + refineBy[i].Query)
                        .replace('&BooleanOperator=or', '')
                        .replace('&BooleanOperator=and', '')
                        + '&BooleanOperator=and';
                }
                
                var aaa = $('<a/>')
                    .attr('href', newUrl)
                    .attr('style', 'white-space:nowrap')
                    .text(refineBy[i].Label)
                    .appendTo(li);
                

                var onFinished = function () {
                    count++;
                    if (count === refineBy.length) {
                        if (list.children('li:visible').length > 0) {
                            msg.hide();
                        } else {
                            msg.text('No matching filters.')
                        }
                    }
                }
                
                $.getJSON(newUrl + '&pageSize=1&excludeCount=true&properties=Uri')
                    .fail(function () { onFinished(); })
                    .done(function (data) {                    
                    if (data.Results.length > 0) {
                        li.show();
                    }
                    onFinished();
                });

            });
        }
    });
}